$('body').show();
$('.version').text(NProgress.version);
NProgress.start();
setTimeout(function () {
    NProgress.done();
    $('.fade').removeClass('out')
}, 1000);
(function () {
    $('img').attr('draggable', 'false');
    $('a').attr('draggable', 'false')
})();

function authenticate(){
    $.ajax({
        url:"/authenticate_",
        type:"GET",
        contentType:"application/json;charset=utf-8",
        dataType:"json",
        success:function (response) {
            if(response.code===200){
                console.log(response);
                $(".login").hide();
                $(".signin").hide();
                $(".publish").show();
                $(".user").show();
                $(".avatar_url").attr("src",response.data.avatar_url);
                $(".username").text(response.data.username);
            }
        },
        error:function (request) {
            console.log(request);
        }
    });
}
function fillingPagination(page,type,size) {
    $.ajax({
        url: "/page/"+type+"/"+page+"/"+size,
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        type: "GET",
        success: function (response) {
            console.log(response.data);
            appendPagination(response.data,type,size);
        },
        error: function (request) {

        }
    });
}

function appendPagination(data,type,size) {
    var method = "fillingMain";
    if(type ==="news"){
        method = "fillingNews"
    }
    var bonus="";
    $(".pagination_").empty();
    var info = "";
    if (data.currentPage !== 1) {
        info+="<li class=\"next-page\"><a href=\"" +
            "javascript:"+method+"("+(data.currentPage-1)+","+"\'"+type+"\'"+"," + size +")"+
            "\">上一页</a></li>";
    }
    $(".pagination_").empty();
    for (var i = 0; i < data.pages.length; i++) {
        if(data.currentPage===data.pages[i]){
            bonus+="active";
        }else {
            bonus="";
        }
        info+="<li class=\"" + bonus + "\"><a href=\"" +
            "javascript:"+method+"("+(data.pages[i])+","+"\'"+type+"\'"+"," + size +")"+
            "\">"+data.pages[i]+"</a></li>";
    }
    if (data.lastPage !== data.currentPage) {
        info+="<li class=\"next-page\"><a href=\"" +
            "javascript:"+method+"("+(data.currentPage+1)+","+"\'"+type+"\'"+"," + size +")"+
            "\">下一页</a></li>";
        info+="<li><span>共"+data.lastPage+"页</span></li>";
    }
    $(".pagination_").append(info);

}

function fillingMain(page,type,size) {
    // debugger;
    if(type==="news"){
        $.ajax({
            url:"/news/"+page+"/"+size,
            dataType:'json',
            contentType:"application/json;charset=utf-8"
        });
        return;
    }
    $.ajax({
        url: "/questions/"+type+"/"+page+"/"+size,
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        type: "GET",
        success: function (response) {
            appendMain(response.data);
            fillingPagination(page,type,size);
        },
        error: function (request) {
            console.log(request);
        }
    });
}

function appendMain(data) {
    $(".main").empty();
    for (var i = 0; i < data.length; i++) {
        var info = "<article class=\"excerpt excerpt-1\" style=\"\">\n" +
            "                    <a class=\"focus\" href=\"" + "/question/"+data[i].id + "\" title=\"社区(LY)\" target=\"_blank\">\n" +
            "                        <img class=\"thumb\"  data-original=\"images/201610181739277776.jpg\"\n" +
            "                             src=\"" + data[i].user.avatar_url + "\" alt=\"###\" style=\"display: inline;height: 64px;width: 64px;\">" +
            "<p style='margin:10px 10px 0px 10px;color: #999999;font-size: 14px;'>" + data[i].user.username + "</p>" +
            "</a>\n" +
            "                    <header>\n" +
            "                        <a class=\"cat\" href=\"#\" title=\"标签\">" + data[i].tags.split(",")[0] + "<i></i></a>\n" +
            "                        <h2><a href=\"" + "/question/" + data[i].id + "\" title=\"用DTcms做一个独立博客网站（响应式模板）\" target=\"_blank\">" + data[i].title + "</a>\n" +
            "                        </h2>\n" +
            "                    </header>\n" +
            "                    <p class=\"meta\">\n" +
            "                        <time class=\"time\"><i class=\"glyphicon glyphicon-time\"></i>" + data[i].createdAt + "</time>\n" +
            "                        <span class=\"views\"><i class=\"glyphicon glyphicon-eye-open\"></i>" + data[i].readCount + "</span>\n" +
            "                        <a class=\"comment\" href=\"##comment\" title=\"评论\" target=\"_blank\">\n" +
            "                            <i class=\"glyphicon glyphicon-comment\"></i>\n" +
            "                            4\n" +
            "                        </a>\n" +
            "                    </p>\n" +
            "                    <p class=\"note\">" + data[i].content + "</p>\n" +
            "                </article>";

        $(".main").append(info);
    }
}

function fillingHotTopic(type,size) {
    $.ajax({
        url: "/hotTopics/"+type+"/"+size,
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        type: "GET",
        success: function (response) {
            appendHotTopic(response.data);
        },
        error: function (request) {
            console.log(request);
        }
    });
}

function appendHotTopic(data) {
    console.log("aaaaa");
    console.log(data);
    $(".hotTopic").empty();
    for (var i = 0; i < data.length; i++) {
        var info = "<li>\n" +
            "                    <a title=\"" + data[i].title + "\" href=\"" + "/question/" + data[i].id + "\" draggable=\"false\"><span class=\"thumbnail\">\n" +
            "                        <img class=\"thumb\" data-original=\"images/201610181739277776.jpg\"\n" +
            "                             src=\"" + data[i].user.avatar_url + "\" alt=\"#\" style=\"display: block;width: 64px;height: 64px;\"\n" +
            "                             draggable=\"false\"></span>\n" +
            "                        <span class=\"text\">" + data[i].title + "</span>\n" +
            "                        <span class=\"muted\">\n" +
            "                            <i class=\"glyphicon glyphicon-time\"></i>\n" + data[i].createdAt +
            "                        </span>\n" +
            "                        <span class=\"muted\">\n" +
            "                            <i class=\"glyphicon glyphicon-eye-open\"></i>" + data[i].readCount +
            "                        </span>\n" +
            "                    </a>\n" +
            "                </li>";
        $(".hotTopic").append(info);
    }
}
function setCookie(name, value, time) {
    var strsec = getsec(time);
    var exp = new Date();
    exp.setTime(exp.getTime() + strsec * 1);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString()
}

function getsec(str) {
    var str1 = str.substring(1, str.length) * 1;
    var str2 = str.substring(0, 1);
    if (str2 == "s") {
        return str1 * 1000
    } else if (str2 == "h") {
        return str1 * 60 * 60 * 1000
    } else if (str2 == "d") {
        return str1 * 24 * 60 * 60 * 1000
    }
}

function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) {
        return unescape(arr[2])
    } else {
        return null
    }
}

$.fn.navSmartFloat = function () {
    var position = function (element) {
        var top = element.position().top,
            pos = element.css("position");
        $(window).scroll(function () {
            var scrolls = $(this).scrollTop();
            if (scrolls > top) {
                $('.header-topbar').fadeOut(0);
                if (window.XMLHttpRequest) {
                    element.css({
                        position: "fixed",
                        top: 0
                    }).addClass("shadow")
                } else {
                    element.css({
                        top: scrolls
                    })
                }
            } else {
                $('.header-topbar').fadeIn(500);
                element.css({
                    position: pos,
                    top: top
                }).removeClass("shadow")
            }
        })
    };
    return $(this).each(function () {
        position($(this))
    })
};
$("#navbar").navSmartFloat();
$("#gotop").hide();
$(window).scroll(function () {
    if ($(window).scrollTop() > 100) {
        $("#gotop").fadeIn()
    } else {
        $("#gotop").fadeOut()
    }
});
$("#gotop").click(function () {
    $('html,body').animate({
        'scrollTop': 0
    }, 500)
});
$("img.thumb").lazyload({
    placeholder: "../images/occupying.png",
    effect: "fadeIn"
});
$(".single .content img").lazyload({
    placeholder: "../images/occupying.png",
    effect: "fadeIn"
});
$('[data-toggle="tooltip"]').tooltip();
// jQuery.ias({
// 	history: false,
// 	container: '.content',
// 	item: '.excerpt',
// 	pagination: '.pagination',
// 	next: '.next-page a',
// 	trigger: '查看更多',
// 	loader: '<div class="pagination-loading"><img src="images/loading.gif" /></div>',
// 	triggerPageThreshold: 5,
// 	onRenderComplete: function() {
// 		$('.excerpt .thumb').lazyload({
// 			placeholder: '../images/occupying.png',
// 			threshold: 400
// 		});
// 		$('.excerpt img').attr('draggable', 'false');
// 		$('.excerpt a').attr('draggable', 'false')
// 	}
// });
$(window).scroll(function () {
    var sidebar = $('.sidebar');
    var sidebarHeight = sidebar.height();
    var windowScrollTop = $(window).scrollTop();
    if (windowScrollTop > sidebarHeight - 60 && sidebar.length) {
        $('.fixed').css({
            'position': 'fixed',
            'top': '70px',
            'width': '360px'
        })
    } else {
        $('.fixed').removeAttr("style")
    }
});
// (function () {
//     var oMenu = document.getElementById("rightClickMenu");
//     var aLi = oMenu.getElementsByTagName("li");
//     for (i = 0; i < aLi.length; i++) {
//         aLi[i].onmouseover = function () {
//             $(this).addClass('rightClickMenuActive');
//         };
//         aLi[i].onmouseout = function () {
//             $(this).removeClass('rightClickMenuActive');
//         }
//     }
//     document.oncontextmenu = function (event) {
//         $(oMenu).fadeOut(0);
//         var event = event || window.event;
//         var style = oMenu.style;
//         $(oMenu).fadeIn(300);
//         style.top = event.clientY + "px";
//         style.left = event.clientX + "px";
//         return false
//     };
//     document.onclick = function () {
//         $(oMenu).fadeOut(100);
//     }
// })();
document.onkeydown = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (e.keyCode === 67 || e.keyCode === 86 || e.keyCode === 13) return true;
    if ((e.keyCode === 123) || (e.ctrlKey) || (e.ctrlKey) && (e.keyCode === 85)) {
        return false
    }
};
try {
    if (window.console && window.console.log) {
        // console.log("\n！\n\n");
        console.log("\n社区(LY)：%c #", "color:red")
    }
} catch (e) {
}
;

function SiteSearch(send_url, divTgs) {
    var str = $.trim($(divTgs).val());
    if (str.length > 0 && str != "请输入关键字") {
        str = str.replace(/\s+/g, "");
        str = str.replace(/[\ |\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?|\，|\。|\：|\；|\·|\~|\！|\、|\《|\》|\‘|\“|\”|\【|\】|\?{|\}|\-|\=|\——|\+|\’|\—|\？]/g, "");
        str = str.replace(/<[^>]*>|/g, "");
        window.location.href = send_url + "?keyword=" + encodeURI(str)
    }
    return false
}

function showSelectionTags() {
    $("#selectionTags").show();
    getTags();
}
function getTags() {
    $.ajax({
        type: "GET",
        url: "/publish/tags",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            $(".category").empty();
            $(".tags").empty();
            var mark = true;
            var bonus="";
            var map = response.data;
            for(var key in map){
                if(mark){
                    bonus+="active";
                }else {
                    bonus="";
                }
                var info_1 = "<li role=\"presentation\" class='" +
                    bonus +
                    "'>\n" +
                    "        <a href=\"" +
                    "#category-"+key +
                    "\" aria-controls=\"messages\" role=\"tab\" data-toggle=\"tab\">" +
                    key +
                    "</a>\n" +
                    "         </li>";
                $(".category").append(info_1);
                var info_2="<div role=\"tabpanel\" class=\"tab-pane " +
                    bonus +
                    "\" id=\"category-"+ key +"\">\n ";
                for(var i=0;i<map[key].length;i++){
                    info_2+=" <span onclick=\"selectTag(this)\" class=\"label label-info\" style=\"margin-left: 5px;\">\n" +
                        "              <span class=\"glyphicon glyphicon-tag\">" +
                        map[key][i].subNames +
                        "               </span>\n" +
                        "        </span>";
                    // console.log(map[key][i]);
                }
                info_2 = info_2  +"</div>";
                $(".tags").append(info_2);
                mark=false;
            }
        },
        error: function (request) {
            console.log(request);
        }
    });
}
function selectTag(e) {
    var tag = e.firstChild.nextSibling.textContent.trim().valueOf();
    var presentValue = $("#questionTags").val();
    var checkedTags =  presentValue.split(",");
    for(var i=0;i<checkedTags.length;i++){
        if(checkedTags[i] == tag){
            return ;
        }
    }
    if(presentValue==""){
        presentValue+=tag;
    }else {
        presentValue+=","+tag;
    }
    $("#questionTags").val(presentValue);

}

function checkQuestion() {
    var title = $("#title").val();
    var content = $("#content").val();
    var tags = $("#questionTags").val();
    if (title.trim() == "" || content.trim() == "" || tags.trim() == "") {
        $("#tip").empty();
        var tip = "<span class='text-danger'>标题,内容或标签为空！</span>";
        $("#tip").append(tip);
        return false;
    }
    return true;
}
function fillingHotTopicNews(size) {
    $.ajax({
        url:"/hotTopics/news/"+size,
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        type:"GET",
        success:function (response) {;
            appendHotTopicNews(response.data);
        },
        error:function (request) {
            console.log(request);
        }
    });
}
function appendHotTopicNews(data) {
    console.log(data);
    $(".hotTopic").empty();
    for(var i=0;i<data.length;i++){
        var info = "<li> <a title=\""+data[i].title+"\" href=\""+"/news/"+data[i].id +"\">\n" +
            "                        <span class=\"thumbnail\">\n" +
            "                            <img class=\"thumb\" data-original=\"images/201610181739277776.jpg\"\n" +
            "                                 src=\""+data[i].imageUrl+"\"\n" +
            "                                 alt=\"#\" style=\"display: block;\">\n" +
            "                        </span>\n" +
            "                        <span class=\"text\" style='height: 100px;overflow:hidden;'>"+data[i].content+"</span>\n" +
            "                        <span class=\"muted\"><i class=\"glyphicon glyphicon-time\">\n" +
            "                        </i>"+data[i].publishTime+"</span>\n" +
            "                        <span class=\"muted\">\n" +
            "                            <i class=\"glyphicon glyphicon-eye-open\"></i>"+data[i].readCount+"</span>\n" +
            "                    </a>\n" +
            "                </li>";
        $(".hotTopic").append(info);
    }

}